package com.tarzan.security.handler;

import com.tarzan.redis.service.RedisService;
import com.tarzan.security.manager.TokenManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Package com.tarzan.security.handler
 * @Title CustomLogoutHandler
 * @Description TODO
 * @Author liujinshan
 * @CreateTime 2021/7/9 14:56
 */
public class CustomLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;

    private RedisService redisService;

    public CustomLogoutHandler(TokenManager tokenManager, RedisService redisService) {
        this.tokenManager = tokenManager;
        this.redisService = redisService;
    }

    /**
     * Causes a logout to be completed. The method must complete successfully.
     *
     * @param request        the HTTP request
     * @param response       the HTTP response
     * @param authentication the current principal details
     */
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String token = request.getHeader("token");
        if (token != null) {
            //清空当前用户缓存中的权限数据
            String userName = tokenManager.getUserFromToken(token);
            redisService.del(userName);
        }
    }
}
